package com.kgc.web;

import com.kgc.dao.AdminCarDao;
import com.kgc.dao.AdminRoomDao;
import com.kgc.dao.UserMgrDao;
import com.kgc.entity.User;
import com.kgc.entity.UserCar;
import com.kgc.entity.UserRoom;
import com.kgc.untils.PageUtils;
import com.kgc.vo.R;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet(name = "userMgrServlet", value = "/userMgrServlet")
public class userMgrServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String opt = request.getParameter("opt");
        UserMgrDao userMgrDao = new UserMgrDao();
        AdminCarDao adminCarDao = new AdminCarDao();
        AdminRoomDao adminRoomDao = new AdminRoomDao();
        if ("list".equals(opt)) {   // 加载用户
            String name = request.getParameter("name");
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");
            PageUtils pageUtils = new PageUtils();
            if (StringUtils.isNotEmpty(page)) {
                pageUtils.setCurrPageNo(Integer.parseInt(page));
            }
            if (StringUtils.isNotEmpty(limit)) {
                pageUtils.setPageSize(Integer.parseInt(limit));
            }
            int totalCount = userMgrDao.totalCount(name);
            pageUtils.init(totalCount);
            List<User> userList = userMgrDao.selectAllUser(pageUtils, name);
            // 加载用户车位和租房信息
            userList.forEach(u -> {
                // 1.查询当前用户对应的车位
                List<UserCar> userCarList = adminCarDao.selectUserByUserId(u.getId());
                if (userCarList != null && userCarList.size() > 0) {
                    u.setCarName(userCarList.stream().map(UserCar::getCarname).collect(Collectors.joining(",")));
                    u.setUserCarList(userCarList);
                } else {
                    u.setCarName("暂无");
                }
                // 1.查询当前用户对应的房屋
                List<UserRoom> userRoomList = adminRoomDao.selectRoomByUserId(u.getId());
                if (userRoomList != null && userRoomList.size() > 0) {
                    u.setRoomName(userRoomList.stream().map(UserRoom::getRoomName).collect(Collectors.joining(",")));
                    u.setUserRoomList(userRoomList);
                } else {
                    u.setRoomName("暂无");
                }
            });
            response.getWriter().write(R.success("用户列表加载成功..", totalCount, userList).toJSON());

        } else if ("add".equals(opt)) {   //添加用户
            String username = request.getParameter("username");
            String phone = request.getParameter("phone");
            String sex = request.getParameter("sex");
            int count = userMgrDao.addUser(new User(username, phone, Integer.parseInt(sex)));
            if (count > 0) {
                response.getWriter().write(R.success("用户添加成功!").toJSON());
            } else {
                response.getWriter().write(R.error("用户添加失败!").toJSON());
            }
        } else if ("delete".equals(opt)) {   //删除用户
            String id = request.getParameter("id");
            int count = userMgrDao.deleteUser(id);
            if (count > 0) {
                response.getWriter().write(R.success("用户删除成功!").toJSON());
            } else {
                response.getWriter().write(R.error("用户删除失败!").toJSON());
            }
        } else if ("edit".equals(opt)) {   // 修改用户
            String id = request.getParameter("id");
            String username = request.getParameter("username");
            String phone = request.getParameter("phone");
            String sex = request.getParameter("sex");
            int count = userMgrDao.editUser(new User(Integer.parseInt(id), username, phone, Integer.parseInt(sex)));
            if (count > 0) {
                response.getWriter().write(R.success("用户修改成功!").toJSON());
            } else {
                response.getWriter().write(R.error("用户修改失败!").toJSON());
            }
        } else if ("stopCar".equals(opt)) {    //停用车位
            // 获取user_car id
            int id = Integer.parseInt(request.getParameter("id"));
            UserCar userCar = adminCarDao.selectUserCarById(id);
            // 1.修改user_car status
            int count = adminCarDao.updateUser(id);
            // 2.修改car状态
            count += adminCarDao.updateCarStatus(userCar.getCarId(), 0);
            if (count > 0) {
                response.getWriter().write(R.success("停用成功!").toJSON());
            } else {
                response.getWriter().write(R.error("停用失败...").toJSON());
            }

        } else if ("stopRoom".equals(opt)) {
            // 获取user_room id
            int id = Integer.parseInt(request.getParameter("id"));
            UserRoom userRoom = adminRoomDao.selectUserRoomById(id);
            // 1.修改user_room status
            int count = adminRoomDao.updateRoomUserStatus(id);
            // 2.修改room状态
            count += adminRoomDao.updateRoomStatus(userRoom.getRoomId(), 0);

            if (count > 0) {
                response.getWriter().write(R.success("停用成功!").toJSON());
            } else {
                response.getWriter().write(R.error("停用失败...").toJSON());
            }
        } else if ("addRoom".equals(opt)) {
            int userId = Integer.parseInt(request.getParameter("userId"));
            int roomId = Integer.parseInt(request.getParameter("roomId"));
            // 修改房屋状态
            int count = adminRoomDao.updateRoomStatus(roomId, 1);
            // 添加用户房屋对应信息
            count += adminRoomDao.addAdminRoom(new UserRoom(userId, roomId, null, null));
            if (count > 0) {
                response.getWriter().write(R.success("分配成功!").toJSON());
            } else {
                response.getWriter().write(R.error("分配失败...").toJSON());
            }
        } else if ("addCar".equals(opt)) { // 分配车位
            int userId = Integer.parseInt(request.getParameter("userId"));
            int carId = Integer.parseInt(request.getParameter("carId"));
            System.out.println("carId = " + carId);
            // 修改车位状态
            int count = adminCarDao.updateCarStatus(carId, 1);
            // 添加用户车位对应信息
            count += adminCarDao.addAdminCar(new UserCar(userId, carId, null, null));
            if (count > 0) {
                response.getWriter().write(R.success("分配成功!").toJSON());
            } else {
                response.getWriter().write(R.error("分配失败...").toJSON());
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
